package com.anycl.customer.service.impl;

import com.anycl.customer.constant.Constants;
import com.anycl.customer.dao.AdminUserRepository;
import com.anycl.customer.entity.AdminUser;
import com.anycl.customer.exception.CustomerException;
import com.anycl.customer.service.AdminUserService;
import com.anycl.customer.vo.AdminUserVo;
import com.anycl.customer.vo.LoginVo;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.Optional;

@Service
public class AdminUserServiceImpl implements AdminUserService {

    private final AdminUserRepository adminUserRepository;

    public AdminUserServiceImpl(AdminUserRepository adminUserRepository) {
        this.adminUserRepository = adminUserRepository;
    }

    @Override
    public AdminUserVo login(LoginVo adminUser) throws CustomerException {
        AdminUserVo adminUserVo = new AdminUserVo();
        if (!adminUser.validate()) {
            throw new CustomerException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }
        Optional<AdminUser> dbUser = adminUserRepository.findByUsername(adminUser.getUsername());
        if (!dbUser.isPresent())
            throw new CustomerException(Constants.ErrorMsg.CAN_NOT_FOUND_RECORD);
        if (!dbUser.get().getPassword().equals(adminUser.getPassword()))
            throw new CustomerException(Constants.ErrorMsg.PASSWORD_ERROR);
        adminUserVo.setStatus(Constants.SuccessMsg.SUCCESS_STATUS);
        adminUserVo.setInfo(Constants.SuccessMsg.SUCCESS);
        adminUserVo.setUsername(adminUser.getUsername());
        return adminUserVo;
    }

    /**
     * 使用时需要判断adminUserVo
     */
    @Override
    public AdminUserVo isLogin(HttpSession httpSession) {
        AdminUserVo adminUserVo = (AdminUserVo) httpSession.getAttribute(Constants.CURRENT_USER);
        return adminUserVo;
    }

    @Override
    public AdminUserVo signIn(LoginVo adminUser, String authCode) throws CustomerException {
        if (authCode != null && !authCode.equals(Constants.AUTH_CODE))
            throw new CustomerException(Constants.ErrorMsg.AUTH_CODE_ERROR);
        if (!adminUser.validate())
            throw new CustomerException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        Optional<AdminUser> dbAdminUser = adminUserRepository.findByUsername(adminUser.getUsername());
        if (dbAdminUser.isPresent())
            throw new CustomerException(Constants.ErrorMsg.EXIST_SAME_RECORD);

        AdminUser newAdminUser = new AdminUser(adminUser.getUsername(), adminUser.getPassword(), Constants.OK_STATUS);
        adminUserRepository.save(newAdminUser);
        return new AdminUserVo(Constants.OK_STATUS, Constants.SuccessMsg.SUCCESS, adminUser.getUsername());
    }

}
